//
//  LoginViewController.m
//  BGM
//
//  Created by liuqin on 2018/11/27.
//  Copyright © 2018年 com.alirtc.demo. All rights reserved.
//

#import "LoginViewController.h"
#import "UserMessageViewController.h"

#import "Common.h"
#import "BGMTextView.h"
#import "AFHTTPSessionManager.h"
#import "UIImageView+WebCache.h"
#import "CommonView.h"
#import "BGMUser.h"
#import "BGMHTTP.h"

#import "SVProgressHUD.h"


@interface LoginViewController ()<BGMTextViewDeleage,UITextFieldDelegate>
@property (nonatomic, strong)UIView *bgView;
@property (nonatomic, strong)UIButton *nextBtn;  //立即进入
@property (nonatomic, assign)BOOL isCangetCore;  //是否可以获取验证码

@property (nonatomic, strong)BGMTextView *iphoneView;  //手机号
@property (nonatomic, strong)BGMTextView *cordView;  //验证码

@property (nonatomic, strong)NSString *cordStr; //验证码

@end

@implementation LoginViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIView animateWithDuration:1 animations:^{
        CGRect rect = self.bgView.frame;
        rect.origin.y = 0;
        self.bgView.frame = rect;
    }];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIImageView *bgImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, SCREENH)];
    bgImage.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:bgImage];
    
    
    UIImageView *topImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREENW, 230)];
    [topImage setImage:[UIImage imageNamed:@"topImage"]];
    [self.view addSubview:topImage];
    
    
    //UI
    self.bgView = [[UIView alloc]initWithFrame:CGRectMake(0, SCREENH, SCREENW, SCREENH)];
    self.bgView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bgView];
    [self.view insertSubview:self.bgView belowSubview:topImage];
    [self addSubViewToBgView];
    
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickBackgroud)];
    [self.view addGestureRecognizer:tap];
    self.view.userInteractionEnabled = YES;
    
    
}
- (void)clickBackgroud{
    [self.iphoneView.myText resignFirstResponder];
    [self.cordView.myText resignFirstResponder];
    
}
- (void)addSubViewToBgView{
    UIImageView *icon = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 60, 30)];
    icon.center = CGPointMake(SCREENW/2, 260);
    [icon setImage:[UIImage imageNamed:@"iconText"]];
    [self.bgView addSubview:icon];


    
   
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, SCREENH-80, SCREENW, 30)];
    label.text = @"真正能帮到您的熟人互助平台";
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = bgmgrayColor;
    label.font = [UIFont systemFontOfSize:13];
    [self.bgView addSubview:label];
    
    self.nextBtn = [[UIButton alloc]initWithFrame:CGRectMake(50, label.frame.origin.y-120, SCREENW-100, 70)];
    [self.nextBtn setBackgroundImage:[UIImage imageNamed:@"loginNormal"] forState:UIControlStateNormal];
    [self.nextBtn setBackgroundImage:[UIImage imageNamed:@"loginSele"] forState:UIControlStateSelected];
    [self.bgView  addSubview:self.nextBtn];
    [self.nextBtn addTarget:self action:@selector(clickNext) forControlEvents:UIControlEventTouchUpInside];
    self.bgView.userInteractionEnabled = YES;
    
    
    self.cordView = [[BGMTextView alloc]initWithFrame:CGRectMake(30, self.nextBtn.frame.origin.y-80, SCREENW-60, 50)];
    [self.cordView.iconImage setImage:[UIImage imageNamed:@"register_2"]];
    [self.cordView.rightBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.cordView.rightBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    self.cordView.rightBtn.hidden = NO;
    self.cordView.myText.placeholder = @"请填写验证码";
    self.cordView.delegate = self;
    self.cordView.myText.keyboardType = UIKeyboardTypePhonePad;
    [self.bgView addSubview:self.cordView];
    
    self.iphoneView = [[BGMTextView alloc]initWithFrame:CGRectMake(30, self.cordView.frame.origin.y-80, SCREENW-60, 50)];
    [self.iphoneView.iconImage setImage:[UIImage imageNamed:@"register_1"]];
    self.iphoneView.myText.placeholder = @"请输入手机号";
    self.iphoneView.myText.keyboardType = UIKeyboardTypeNumberPad;
//    self.iphoneView.myText.delegate = self;
    
     [self.iphoneView.myText addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.bgView addSubview:self.iphoneView];
    
  
    
}

- (void)textFieldDidChange:(UITextField *)textField

{
//    NSLog(@"-----%d",(int)textField.text.length);
    if (textField.text.length >= 11) {
        textField.text = [textField.text substringToIndex:11];
        self.isCangetCore = YES;
        [self.cordView.rightBtn setBackgroundColor:bgmColor(250, 203, 11)];
        
    }else{
        self.isCangetCore = NO;
        [self.cordView.rightBtn setBackgroundColor:bgmColor(224, 224, 224)];
        
    }
    
}

//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    NSLog(@"-----%d",(int)textField.text.length);
//    if (textField.text.length >11) {
//        textField.text = [textField.text substringToIndex:11];
//        self.isCangetCore = YES;
//        [self.cordView.rightBtn setBackgroundColor:bgmColor(250, 203, 11)];
//
//    }else{
//        self.isCangetCore = NO;
//        [self.cordView.rightBtn setBackgroundColor:bgmColor(224, 224, 224)];
//
//    }
//    return YES;
//
//}

#pragma mark 获取验证码
- (void)getCoreNumber{
    
    if(self.isCangetCore){
        [self.iphoneView.myText resignFirstResponder];
        [self startTimeDown];
        self.nextBtn.selected = YES;
        NSDictionary *params = @{@"phoneNum":self.iphoneView.myText.text};
        [BGMHTTP requestWithMethodName:@"login/getsmsCode" parameters:params completion:^(BOOL success, NSError *error, NSDictionary *result) {
            [self getCode:result];
        }];
    }
}
- (void)getCode:(NSDictionary *)dic{
    dispatch_async(dispatch_get_main_queue(), ^{
        NSString *code = [NSString stringWithFormat:@"%@",[dic objectForKey:@"code"]];
        if ([code isEqualToString:@"200"]) {
            self.cordStr = [NSString stringWithFormat:@"%@",[dic objectForKey:@"data"]];
//            self.cordView.myText.text = self.cordStr;
            [SVProgressHUD showSuccessWithStatus:@"验证码已发送,请查收"];
        }else{
            [SVProgressHUD showErrorWithStatus:@"服务器错误"];
        }
       
    });   
}
- (void)gotoRegisterVC{
 
    dispatch_async(dispatch_get_main_queue(), ^{
        UserMessageViewController *vc = [[UserMessageViewController alloc]init];
        vc.iphone = self.iphoneView.myText.text;
        [self.navigationController pushViewController:vc animated:YES];
    });
}
- (void)gotoMainVC{
    
    dispatch_async(dispatch_get_main_queue(), ^{
        UserMessageViewController *vc = [[UserMessageViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    });
    

}


- (void)getData:(NSDictionary *)dic{
    NSString *code = [NSString stringWithFormat:@"%@",[dic objectForKey:@"code"]];
    if ([code isEqualToString:@"300"]) {  //300去注册
        [self gotoRegisterVC];
    }else if([code isEqualToString:@"200"]){ //进入首页
        dispatch_async(dispatch_get_main_queue(), ^{
           
            NSDictionary *userDic = [dic objectForKey:@"data"];
            BGMUser *user = [BGMUser shareInstance];
            user.birthday = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"birthday"]];
            user.city = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"city"]];
            user.gender = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"gender"]];
            user.headImage = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"headImage"]];
            user.imageArray = [userDic objectForKey:@"image"];
            user.industry = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"industry"]];
            user.name = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"name"]];
            user.personalLabelArray = [userDic objectForKey:@"personalLabel"];
            user.phone = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"phone"]];
            user.spectralValue = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"spectralValue"]];
            user.userId = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"usersId"]];
            user.userToken = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"token"]];
            user.imToken = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"imToken"]];
            
            NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
            [ud setObject:@"1" forKey:ISLOGINKEY];//登录成功
            [ud setObject:userDic forKey:usermessage];//登录成功
            [ud synchronize];
            
            
            user.userId = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"usersId"]];
            user.userToken = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"token"]];
            user.imToken = [NSString stringWithFormat:@"%@",[userDic objectForKey:@"imToken"]];
            
            
            [[NSNotificationCenter defaultCenter]postNotificationName:@"gotoMainVC" object:nil];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"LoginSuccess" object:nil];
        });

    }else{
        UIAlertController *alert = [CommonView getCommonAlert:@"登录失败" message:[NSString stringWithFormat:@"%@",code] ok:@"确实" cancel:@"取消" completed:^(NSInteger index) {
            
        }];
        
        [self presentViewController:alert animated:YES completion:nil];
    }
}
- (void)startTimeDown
{
    
    __block int timeout = 59;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if (timeout <= 0){
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.cordView.myLabel.hidden = YES;
                self.cordView.rightBtn.hidden = NO;
                [self.cordView.rightBtn setTitle:@"再次获取" forState:UIControlStateNormal];
 
            });
        } else {
            NSString *strTime = [NSString stringWithFormat:@"%ds", timeout];
            dispatch_async(dispatch_get_main_queue(), ^{
                self.cordView.myLabel.hidden = NO;
                self.cordView.rightBtn.hidden = YES;
                self.cordView.myLabel.text = strTime;
 
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
    
}

#pragma mark 立即进入
- (void)clickNext{
  
    if (!self.nextBtn.selected) {
        [SVProgressHUD showInfoWithStatus:@"请先获取登录验证码"];
        return;
    }
    if (self.cordStr.length==0) {
        [SVProgressHUD showInfoWithStatus:@"请重新获取登录验证码"];
        return;
    }
    
    NSDictionary *param = @{@"phoneNumber":self.iphoneView.myText.text,@"smsCode":self.cordView.myText.text};
    [BGMHTTP requestWithMethodName:@"login/checkRegister" parameters:param completion:^(BOOL success, NSError *error, NSDictionary *result) {
        [self getData:result];
    }];
    
}


@end
